package com.parking.carsystem.parkingchargesystem.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.parking.carsystem.parkingchargesystem.R;
import com.parking.carsystem.parkingchargesystem.adapter.InvoiceMessageAdapter;
import com.parking.carsystem.parkingchargesystem.common.Constant;
import com.parking.carsystem.parkingchargesystem.module.GroupListModule;
import com.parking.carsystem.parkingchargesystem.module.InvoiceMessageTitle;
import com.parking.carsystem.parkingchargesystem.view.OnItemMenuClickListener;
import com.parking.carsystem.parkingchargesystem.view.SwipeMenu;
import com.parking.carsystem.parkingchargesystem.view.SwipeMenuBridge;
import com.parking.carsystem.parkingchargesystem.view.SwipeMenuCreator;
import com.parking.carsystem.parkingchargesystem.view.SwipeMenuItem;
import com.parking.carsystem.parkingchargesystem.view.SwipeRecyclerView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class InvoiceMessageActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.text)
    TextView text;
    @BindView(R.id.invoice_company_message)
    SwipeRecyclerView invoiceCompanyMessage;
    @BindView(R.id.setting)
    TextView setting;
    ArrayList<InvoiceMessageTitle.DataBean> userData;
    ArrayList<InvoiceMessageTitle.DataBean> companyData;
    ArrayList<InvoiceMessageTitle.DataBean> inVoiceData;
    @BindView(R.id.tips)
    TextView tips;
    @BindView(R.id.invoice_record)
    TextView invoice_record;
    @BindView(R.id.draw_invoice)
    TextView draw_invoice;
    private InvoiceMessageAdapter companyAdapter;
    private boolean choose;
    InvoiceMessageTitle.DataBean tempDataBean;
    private String recordId;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_invoice;
    }

    @Override
    public void initView() {
        choose = getIntent().getBooleanExtra("choose", false);
        recordId = getIntent().getStringExtra("recordId");
        if (choose) {
            draw_invoice.setVisibility(View.VISIBLE);
        }
        back.setVisibility(View.VISIBLE);
        text.setText("发票信息");
        setting.setVisibility(View.VISIBLE);
        setting.setText("+新增发票");
        setting.setOnClickListener(this);
        if (userData == null) {
            userData = new ArrayList<>();
        }
        if (companyData == null) {
            companyData = new ArrayList<>();
        }
        if (inVoiceData == null) {
            inVoiceData = new ArrayList<>();
        }
        draw_invoice.setOnClickListener(this);
        invoice_record.setOnClickListener(this);
    }

    @Override
    public void initData() {
        invoiceCompanyMessage.setLayoutManager(new LinearLayoutManager(this));
        companyAdapter = new InvoiceMessageAdapter(companyData, this, choose);
        invoiceCompanyMessage.setOnItemMenuClickListener(new OnItemMenuClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge menuBridge, int position) {
                menuBridge.closeMenu();
                InvoiceMessageTitle.DataBean dataBean = inVoiceData.get(position);
                int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
                int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。

                if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
//                    showToast("list第" + position + "; 右侧菜单第" + menuPosition);
                    inVoiceData.remove(dataBean);
                    companyAdapter.setDatas(inVoiceData);
                    //直接删除列表,不同步网络请求
                    deleteInvoiceMsg(dataBean);
                } else if (direction == SwipeRecyclerView.LEFT_DIRECTION) {
//                    showToast("list第" + position + "; 左侧菜单第" + menuPosition);
                }
            }
        }); // Item的Menu点击。
        invoiceCompanyMessage.setSwipeMenuCreator(new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int position) {
                int width = getResources().getDimensionPixelSize(R.dimen.dp_70);

                // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
                // 2. 指定具体的高，比如80;
                // 3. WRAP_CONTENT，自身高度，不推荐;
                int height = ViewGroup.LayoutParams.MATCH_PARENT;

                // 添加左侧的，如果不添加，则左侧不会出现菜单。
            /*{
                SwipeMenuItem addItem = new SwipeMenuItem(getActivity()).setBackground(
                        R.drawable.selector_green).setImage(R.drawable.ic_action_add).setWidth(width).setHeight(height);
                swipeLeftMenu.addMenuItem(addItem); // 添加一个按钮到左侧菜单。

                SwipeMenuItem closeItem = new SwipeMenuItem(BaseDragActivity.this).setBackground(
                        R.drawable.selector_red).setImage(R.drawable.ic_action_close).setWidth(width).setHeight(height);

                swipeLeftMenu.addMenuItem(closeItem); // 添加一个按钮到左侧菜单。
            }*/

                // 添加右侧的，如果不添加，则右侧不会出现菜单。
                if (companyAdapter.getItemViewType(position) == Constant.VIEWTYPE_THREE) {
                    {
                        SwipeMenuItem deleteItem = new SwipeMenuItem(InvoiceMessageActivity.this).setBackground(
                                R.drawable.parking_plate_red)
//                        .setImage(R.drawable.ic_action_delete)
                                .setText("删除")
                                .setTextColor(Color.WHITE)
                                .setWidth(width)
                                .setHeight(height);
                        swipeRightMenu.addMenuItem(deleteItem);// 添加一个按钮到右侧侧菜单。

                /*SwipeMenuItem closeItem = new SwipeMenuItem(BaseDragActivity.this).setBackground(
                        R.drawable.selector_purple).setImage(R.drawable.ic_action_close).setWidth(width).setHeight(height);
                swipeRightMenu.addMenuItem(closeItem); // 添加一个按钮到右侧菜单。*/
                    }
                }
            }
        }); // 菜单创建器。
//                meCarMessage.setOnItemMoveListener(getItemMoveListener());// 监听拖拽和侧滑删除，更新UI和数据源。
//                meCarMessage.setOnItemStateChangedListener(mOnItemStateChangedListener); // 监听Item的手指状态，拖拽、侧滑、松开。
//                meCarMessage.setLongPressDragEnabled(true); // 长按拖拽，默认关闭。
//                meCarMessage.setItemViewSwipeEnabled(false); // 滑动删除，默认关闭。
        invoiceCompanyMessage.setOnItemClickListener(new com.parking.carsystem.parkingchargesystem.view.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int adapterPosition) {
                InvoiceMessageTitle.DataBean dataBean = inVoiceData.get(adapterPosition);
                Log.d("parking", "第" + adapterPosition + "个");
                if (!dataBean.type.equals("10")) {
                    if (choose) {
                        if (dataBean.choose) {
                            tempDataBean.choose = false;
                        } else {
                            if (tempDataBean != null) {
                                tempDataBean.choose = false;
                            }
                            dataBean.choose = true;
                            tempDataBean = dataBean;
                        }
                    }
                    companyAdapter.notifyDataSetChanged();
//                    showToast("点击发票");
//                    Intent intent = new Intent(getActivity(), LicensePlateAddActivity.class);
//                    startActivityForResult(intent, Constant.ADDPARKINGCODE);
                } else {
                    //提示的不需要点击
                }
            }
        });
        invoiceCompanyMessage.setAdapter(companyAdapter);
        getHistoryInvoice();
    }

    private void deleteInvoiceMsg(InvoiceMessageTitle.DataBean dataBean) {
        //删除指定分组的车牌
        OkGo.<String>delete(Constant.url + Constant.INVOICEREMOVE + dataBean.recordId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }

                    @Override
                    public void onError(Response<String> response) {
                    }
                });
    }

    /**
     * 查看用户发票抬头
     */
    private void getHistoryInvoice() {
        showLoading();
        OkGo.<String>get(Constant.url + Constant.INVOICELISTTITLE)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        stopLoading();
                        Gson gson = new Gson();
                        InvoiceMessageTitle invoiceMessageTitle = gson.fromJson(response.body(), InvoiceMessageTitle.class);
                        if (invoiceMessageTitle.code == 200) {
                            if (invoiceMessageTitle.data != null && invoiceMessageTitle.data.size() > 0) {
                                tips.setVisibility(View.VISIBLE);
                                //有数据
                                List<InvoiceMessageTitle.DataBean> data = invoiceMessageTitle.data;
                                for (InvoiceMessageTitle.DataBean datum : data) {
                                    if (choose) {
                                        datum.choose = false;
                                    }
                                    if (TextUtils.equals(datum.type, "01")) {
                                        //单位
                                        companyData.add(datum);
                                    } else if (datum.type.equals("03")) {
                                        //个人
                                        userData.add(datum);
                                    }
                                }
                                if (companyData.size() > 0) {
                                    InvoiceMessageTitle.DataBean dataBean = new InvoiceMessageTitle.DataBean();
                                    dataBean.name = "单位";
                                    dataBean.type = "10";
                                    inVoiceData.add(dataBean);
                                    inVoiceData.addAll(companyData);
                                }
                                if (userData.size() > 0) {
                                    InvoiceMessageTitle.DataBean dataBean1 = new InvoiceMessageTitle.DataBean();
                                    dataBean1.name = "个人";
                                    dataBean1.type = "10";
                                    inVoiceData.add(dataBean1);
                                    inVoiceData.addAll(userData);
                                }
                                companyAdapter.setDatas(inVoiceData);
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        stopLoading();
                    }
                });
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.setting:
                intent = new Intent(this, AddInvoiceActivity.class);
                startActivityForResult(intent, 0);
                break;
            case R.id.draw_invoice:
                //开具发票
                if (tempDataBean != null) {
                    createInvoice();
                } else {
                    showToast("请选择发票");
                }
                break;
            case R.id.invoice_record:
                intent = new Intent(this, InvoiceRecordActivity.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * 开具发票接口
     */
    private void createInvoice() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("orderRecordId", recordId);
        hashMap.put("titleId", tempDataBean.recordId);
        JSONObject jsonObject = new JSONObject(hashMap);
        showLoading();
        OkGo.<String>post(Constant.url + Constant.INVOICECREATEINVOICE)
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        stopLoading();
//                        http://218.2.192.212:9000/aisino_cms/testpdf//150300201007206301/2020/04/08/7/bdd8d4b68d3b4f6a6230_1586328667672.pdf
                        setResult(Constant.MONTHLYSUBSCRIPTIONPARKING);
                        finish();

                    }

                    @Override
                    public void onError(Response<String> response) {
                        stopLoading();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (Constant.MONTHLYSUBSCRIPTIONPARKING == resultCode) {
            userData.clear();
            companyData.clear();
            inVoiceData.clear();
            getHistoryInvoice();
        }
    }
}
